// pages/carts/carts.js
import {
  hotApi,
  cartcountApi,
  cartlistApi,
  cartNumApi,
  cartDelApi,
  delCartApi
} from '../../http/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsNumber: 0,
    loginState: false,
    hotData: [],
    goodsCount: 0,
    totalPrice: 0,
    valid: [],
    invalidList:[],
    allchecked: false,
    allCount: 0,
    goodsCheck: false,
    manageState: true,
    checkList: []
  },
  toLoginPage() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  toPayment() {
    console.log(this.chooseList());
    let chooseList = this.chooseList()
    if (chooseList.length !== 0) {
      let id = []
      chooseList.map(item => {
        id.push(item.id)
      })
      console.log(id.toString());
      wx.navigateTo({
        url: `/pages/productDetails/payment/payment?cartId=${id.toString()}`,
      })
    } else {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      })
    }
  },
  toproductDetails(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/productDetails/productDetails?id=' + id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    hotApi({
      page: 1,
      limit: 20
    }).then(res => {
      console.log(res.data);
      this.setData({
        hotData: res.data
      })
    })

  },
  getCartList() {
    cartlistApi().then(res => {
      console.log(res);
      let {
        valid,invalid
      } = res.data
      this.setData({
        valid,
        invalidList:invalid
      })
      console.log(this.data.valid);

    })
    cartcountApi().then(res => {
      let goodsCount = res.data.count
      this.setData({
        goodsCount
      })
    })
  },
  chooseList() {
    let _self = this;
    let chooseList = []
    let checkList = _self.data.checkList
    let valid = _self.data.valid
    checkList.map(item => {
      console.log(valid);
      console.log(item);
      chooseList.push(valid[item])
    })
    return chooseList
  },
  removeGoods(e) {
    let id = e.currentTarget.dataset.id
    let num = e.currentTarget.dataset.num
    let allCount = this.data.allCount;
    if (num <= 1) {
      return wx.showToast({
        title: '不能再减啦！',
        icon: 'error'
      })
    } else {
      num--
      cartNumApi({
        id,
        number: num
      }).then(res => {
        console.log(res);
        cartlistApi().then(res => {
          console.log(res);
          let {
            valid
          } = res.data
          this.setData({
            valid
          })
          console.log(this.data.valid);
          let chooseList = this.chooseList();
          console.log(chooseList);
          allCount = 0
          console.log(valid);
          chooseList.map(item => {
            console.log(item);
            allCount += item.cartNum * item.productInfo.price
          })
          this.setData({
            allCount
          })
        })
        cartcountApi().then(res => {
          let goodsCount = res.data.count
          this.setData({
            goodsCount
          })
        })
      })
    }
  },
  addGoods(e) {
    let id = e.currentTarget.dataset.id
    let num = e.currentTarget.dataset.num
    let allCount = this.data.allCount;
    let valid = this.data.valid
    num++
    console.log(num);
    cartNumApi({
      id,
      number: num
    }).then(res => {
      console.log(res);
      cartlistApi().then(res => {
        console.log(res);
        let {
          valid
        } = res.data
        this.setData({
          valid
        })
        console.log(this.data.valid);
        let chooseList = this.chooseList();
        console.log(chooseList);
        allCount = 0
        console.log(valid);
        chooseList.map(item => {
          console.log(item);
          allCount += item.cartNum * item.productInfo.price
        })
        this.setData({
          allCount
        })
      })
      cartcountApi().then(res => {
        let goodsCount = res.data.count
        this.setData({
          goodsCount
        })
      })
    })
  },
  checkboxChange(e) {
    let list = e.detail.value
    console.log(list);
    this.setData({
      checkList: list
    })
    if (list.length == this.data.valid.length) {
      this.setData({
        allchecked: true
      })
    } else {
      this.setData({
        allchecked: false
      })
    }
    let allCount = 0
    let valid = this.data.valid
    list.map(item => {
      allCount += valid[item].cartNum * valid[item].productInfo.price
    })
    this.setData({
      allCount
    })
  },
  allcheckedFun() {
    this.setData({
      allchecked: !this.data.allchecked
    })
    if (this.data.allchecked) {
      this.setData({
        goodsCheck: true
      })
      let allCount = 0
      let valid = this.data.valid
      let list = []
      valid.map((item,index)=>{
        list.push(index.toString())
      })
      this.setData({
        checkList: list
      })
      valid.map(item => {
        allCount += item.cartNum * item.productInfo.price
      })
      this.setData({
        allCount
      })

    } else {
      this.setData({
        goodsCheck: false,
        allCount: 0
      })
    }
  },
  changeManage() {
    this.setData({
      manageState: !this.data.manageState
    })
  },
  delNow(e) {
    let _self = this
    let delList = []
    let checkList = this.data.checkList
    let valid = this.data.valid
    checkList.map(item => {
      let id = valid[item].id
      delList.push(id)
    })
    if (delList.length == 0) {
      wx.showToast({
        title: '未选择商品！',
        icon: 'none'
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确认删除购物车商品？',
        success(res) {
          if (res.confirm) {
            console.log(delList)
            cartDelApi({
              ids: delList
            }).then(() => {
              _self.getCartList()
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  // 跳转商品详情页
  prodetail(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id
    console.log(id);
    wx.navigateTo({
      url: '../productDetails/productDetails?id=' + id,
    })
  },
  //清空无效商品
  empty(){
    let _self = this;
    let list = [];
    let arr = _self.data.invalidList;
    arr.map(item=>{
      list.push(item.id);
    })
    console.log(list);
    async function del(){
      //删除勾选商品
      await delCartApi({
        ids: list
      }).then(res=>{
      })
      await _self.getCart();
      await cartNumApi().then(res=>{
        console.log(res.count);
        _self.setData({
          cartNum: res.count
        })
      })
    }
    this.getCartList()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (wx.getStorageSync('token')) {
      this.setData({
        loginState: true
      })
      this.getCartList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})